package com.sky.controller.user;


import com.sky.context.BaseContext;
import com.sky.entity.AddressBook;
import com.sky.result.Result;
import com.sky.service.AddressBookService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@Slf4j
@Api(tags = "地址簿模块管理")
@RequestMapping("/user/addressBook")
public class AddressBookController {

    @Autowired
    private AddressBookService addressBookService;

    @PostMapping
    @ApiOperation("新增地址簿")
    public Result save(@RequestBody AddressBook addressBook) {
        log.info("新增地址簿");
        addressBookService.insertAddressBook(addressBook);
        return Result.success();
    }

    @GetMapping("/list")
    @ApiOperation("查询地址簿列表")
    public Result<List<AddressBook>> list(){
        log.info("查询地址簿列表");
        AddressBook addressBook = new AddressBook();
        addressBook.setUserId(BaseContext.getCurrentId());
        List<AddressBook> list=addressBookService.list(addressBook);
        return Result.success(list);
    }

    @GetMapping("/default")
    @ApiOperation("查询默认地址簿")
    public Result defaultAddressBook(){
        log.info("查询默认地址簿");
        AddressBook addressBook=new AddressBook();
        addressBook.setIsDefault(1);
        addressBook.setUserId(BaseContext.getCurrentId());
        List<AddressBook> list = addressBookService.list(addressBook);
        if(list.size()>0){
            return Result.success(list.get(0));
        }else{
            return Result.error("没有默认地址簿");
        }
    }

    @PutMapping("/default")
    @ApiOperation("设置默认地址簿")
    public Result setDefaultAddressBook( @RequestBody AddressBook addressBook){
        log.info("设置默认地址簿");
        addressBookService.setDefaul(addressBook);
        return Result.success();
    }

    @GetMapping("/{id}")
    @ApiOperation("根据id查询地址信息")
    public Result<AddressBook> getById(@PathVariable Long id) {
        log.info("根据id查询地址信息");
        AddressBook addressBook = addressBookService.getById(id);
        return Result.success(addressBook);
    }

    @PutMapping
    @ApiOperation("根据id修改地址信息")
    public Result update(@RequestBody AddressBook addressBook){
        log.info("根据id修改地址信息");
        addressBookService.update(addressBook);
        return Result.success();
    }

    @DeleteMapping
    public Result delete(@RequestParam Long id){
        log.info("根据id删除地址信息");
        addressBookService.delete(id);
        return Result.success();
    }


}


